<template>
  <span
    v-if="!editing"
    @click="startEdit"
    class="editable-cell-text"
    :style="displayStyle"
    :class="[!displayText ? 'editable-cell-placeholder' : '', displayText ? 'editable-cell-solid' : 'editable-cell-dashed']"
  >{{ displayText || placeholder || '请选择' }}</span>
  <el-select
    v-else
    v-model="innerValue"
    @change="onChange"
    @blur="stopEdit"
    filterable
    size="small"
    style="width: 100px"
    ref="selectRef"
    :placeholder="placeholder || '请选择'"
    :disabled="disabled"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
      :style="item.style || ''"
    />
  </el-select>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, onMounted, nextTick } from "vue";
const props = defineProps({
  modelValue: [String, Number],
  options: {
    type: Array,
    required: true
  },
  displayText: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  displayStyle: {
    type: [String, Object],
    default: ''
  }
});
const emit = defineEmits(["update:modelValue", "change"]);
const editing = ref(false);
const innerValue = ref(props.modelValue);
const selectRef = ref();

watch(() => props.modelValue, v => (innerValue.value = v));

function startEdit() {
  if (props.disabled) return;
  editing.value = true;
  nextTick(() => {
    selectRef.value && selectRef.value.focus && selectRef.value.focus();
  });
}
function stopEdit() {
  editing.value = false;
}
function onChange(val: any) {
  emit("update:modelValue", val);
  emit("change", val);
  stopEdit();
}
</script>

<style scoped>
.editable-cell-text {
  cursor: pointer;
  display: inline-block;
  min-width: 80px;
  padding: 2px 4px;
  border-radius: 4px;
  transition: border-color 0.2s, border-style 0.2s;
}
.editable-cell-dashed {
  border: 1px dashed #e0e0e0;
}
.editable-cell-solid {
  border: 1px solid #888888;
}
.editable-cell-text:hover {
  border-color: #409eff;
}
.editable-cell-placeholder {
  color: #bdbdbd;
}
</style> 